package com.yc.jpyy.mobile.controller;

import java.io.BufferedOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.config.Config;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.base.util.WXPayUtil;
import com.yc.jpyy.base.util.XMLUtil;
import com.yc.jpyy.mobile.dao.BizDao;
import com.yc.jpyy.mobile.service.BizService;


@Controller
@RequestMapping(value = "/WXPay")
public class WXPayController extends BaseController{

	@Autowired
	private BizService bizService;
	@Autowired
	private BizDao bizDao;
	
	/*
	 * 调用微信统一下单接口返回订单信息接口
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getOrderInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String getOrderInfo(HttpServletRequest request)
			throws UnsupportedEncodingException {
		RestResponse response = new RestResponse();
		try {
			 //商品描述
			 String body = request.getParameter("body");
			 //商品详情
			 //String detail = request.getParameter("detail"); 
			 //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
	         //String attach =   
			 //商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
	         String out_trade_no = request.getParameter("out_trade_no"); 
	         //订单总金额，单位为分，详见支付金额
	         String total_fee = request.getParameter("total_fee");  
	         //用户端实际ip
	         String spbill_create_ip = request.getParameter("spbill_create_ip");
	         String time_start = WXPayUtil.getWXTimeStart();
	         String time_expire = WXPayUtil.getWXTimeExpire();
	       //参数：开始生成签名
	         SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
	         parameters.put("appid", Config.getWXPayAppId());
	         parameters.put("mch_id", Config.getMchId());
	         parameters.put("nonce_str", WXPayUtil.CreateNoncestr());
	         parameters.put("body", body);
	         //parameters.put("detail", detail);
	         //parameters.put("attach", attach);
	         parameters.put("out_trade_no", out_trade_no);
	         parameters.put("total_fee", total_fee);
	         parameters.put("time_start", time_start);
	         parameters.put("time_expire", time_expire);
	         parameters.put("notify_url", Config.getWXNotifyUrl());
	         parameters.put("trade_type", "APP");
	         parameters.put("spbill_create_ip", spbill_create_ip);
	         
	         String sign = WXPayUtil.createSign("UTF-8", parameters);
	         System.out.println("签名是："+sign);
	         parameters.put("sign", sign);
	         // 封装请求参数结束
	         String requestXML = WXPayUtil.getRequestXml(parameters); // 获取xml结果
	         // 调用统一下单接口
	         String result = WXPayUtil.httpsRequest(Config.getWXPayUrl(), "POST",requestXML);
	         //再次签名
	         SortedMap<Object, Object> parMap = WXPayUtil.startWXPay(result);
	         if (parMap != null)
	            {
	              //返回订单信息
	                response.setErrorcode(0);
	                response.setData(JSON.toJSONString(parMap));
	            } else
	            {
	            	response.setErrorcode(1);
	            	response.setMessage("获取支付订单失败--验签失败！");
	            }
	         
		} catch (Exception e) {
			response.setErrorcode(1);
			response.setMessage("获取支付订单失败！");
		}finally {
			return response.toJSON();
		}		
	}
	
	/*
	 * 异步回调通知接口
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/notify", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String notify(HttpServletRequest request, HttpServletResponse response) throws Exception{
			String result = WXPayUtil.reciverWx(request); // 接收到异步的参数
	        Map<String, String> m = new HashMap<String, String>();// 解析xml成map
	        if (m != null && !"".equals(m))
	        {
	            m = XMLUtil.doXMLParse(result);
	        }
	        // 过滤空 设置 TreeMap
	        SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
	        Iterator it = m.keySet().iterator();
	        while (it.hasNext())
	        {
	            String parameter = (String) it.next();
	            String parameterValue = m.get(parameter);
	            String v = "";
	            if (null != parameterValue)
	            {
	                v = parameterValue.trim();
	            }
	            packageParams.put(parameter, v);
	        }
	        // 判断签名是否正确
	        String resXml = "";
	        if (WXPayUtil.isTenpaySign("UTF-8", packageParams))
	        {
	            if ("SUCCESS".equals((String) packageParams.get("return_code")))
	            {
	                // 如果返回成功
	                String mch_id = (String) packageParams.get("mch_id"); // 商户号
	                String out_trade_no = (String) packageParams.get("out_trade_no"); // 商户订单号
	                String total_fee = (String) packageParams.get("total_fee");
	                // String transaction_id = (String)
	                // packageParams.get("transaction_id"); // 微信支付订单号
	                // 查询订单 根据订单号查询订单
	                String orderId = out_trade_no.substring(0, out_trade_no.length() - WXPayUtil.TIME.length());
	               //Orders orders = ordersMapper.selectByPrimaryKey(Integer.parseInt(orderId));

	                // 验证商户ID 和 价格 以防止篡改金额
	                if (Config.getMchId().equals(mch_id) 
	                		//&& orders != null
	                // &&
	                // total_fee.trim().toString().equals(orders.getOrderAmount())
	                //  实际项目中将此注释删掉，以保证支付金额相等
	                )
	                {
	                    //写相应的业务逻辑
	                    // ordersMapper.updatePayStatus(Integer.parseInt(orderId));
	                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
	                            + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
	                } else
	                {
	                    resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
	                            + "<return_msg><![CDATA[参数错误]]></return_msg>" + "</xml> ";
	                }
	            } else // 如果微信返回支付失败，将错误信息返回给微信
	            {
	                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
	                        + "<return_msg><![CDATA[交易失败]]></return_msg>" + "</xml> ";
	            }
	        } else
	        {
	            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
	                    + "<return_msg><![CDATA[通知签名验证失败]]></return_msg>" + "</xml> ";
	        }

	        // 处理业务完毕，将业务结果通知给微信
	        // ------------------------------
	        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
	        out.write(resXml.getBytes());
	        out.flush();
	        out.close();
	        return resXml;
	}
}
